<template>
  <div>
    <input id="excel-upload-input" ref="excel-upload-input" type="file" accept=".xlsx, .xls" @change="handleClick">
    <div id="drop" @drop="handleDrop" @dragover="handleDragover" @dragenter="handleDragover">
      拖拽文件到这里
      <el-button :loading="loading" style="margin-left:16px;" size="mini" type="primary" @click="handleUpload">{{filename}}</el-button>
    </div>
  </div>
</template>

<script>

export default {
  props: {
    beforeUpload: Function,
    onSuccess: Function
  },
  data() {
    return {
      loading: false,
      filename:'选择文件'
    }
  },
  methods: {
    handleDrop(e) {
      e.stopPropagation()
      e.preventDefault()
      if (this.loading) return
      const files = e.dataTransfer.files
      if (files.length !== 1) {
        this.$message.error('一次支持一个文件!')
        return
      }
      const rawFile = files[0] // only use files[0]
      this.upload(rawFile)
      e.stopPropagation()
      e.preventDefault()
    },
    handleDragover(e) {
      e.stopPropagation()
      e.preventDefault()
      e.dataTransfer.dropEffect = 'copy'
    },
    handleUpload() {
      document.getElementById('excel-upload-input').click()
    },
    handleClick(e) {
      const files = e.target.files
      const rawFile = files[0] // only use files[0]
      if (!rawFile) return
      this.upload(rawFile)
    },
    upload(rawFile) {
      this.$refs['excel-upload-input'].value = null // fix can't select the same excel
      if (!this.beforeUpload) {
        this.notReadFile(rawFile)
        return
      }
      const before = this.beforeUpload(rawFile)
      if (before) {
          this.notReadFile(rawFile)
      }
    },
    notReadFile(rawFile){
    this.filename = rawFile.name
    let formData = new FormData() || new window.FormData()
        formData.append('import_file',rawFile)
        this.onSuccess && this.onSuccess(formData)
    },
  }
}
</script>

<style scoped>
#excel-upload-input{
  display: none;
  z-index: -9999;
}
#drop{
  border: 2px dashed #bbb;
  width: 600px;
  height: 160px;
  line-height: 160px;
  margin: 0 auto;
  font-pageSize: 24px;
  border-radius: 5px;
  text-align: center;
  color: #bbb;
  position: relative;
}
</style>
